import api from "@/utils/api";
import { useRouter } from "vue-router";
const router = useRouter();
export const user = defineStore("user", {
  state: () => {
    return {
      showLogin: false,
      showRegister: false,
      userInfo: "",
      token: "",
    };
  },
  actions: {
    login() {
      this.showLogin = !this.showLogin;
    },
    async loginApi(data: { username: string; pwd: string }) {
      return new Promise((resolve, reject) => {
        api
          .post("/login", data)
          .then((res) => {
            this.userInfo = res;
            this.token = res.token;
            resolve(res);
          })
          .catch((error) => {
            return reject(error);
          });
      });
    },
    async logout() {
      return new Promise((resolve, reject) => {
        api.get("/login/logout").then((res) => {
          this.cleanUser();
          navigateTo("/");
          resolve(res);
        });
      });
    },
    cleanUser() {
      this.userInfo = "";
      this.token = "";
    },
  },
  persist: true,
});
